package com.bridgeintelligent.tag.webserver.logs;

import com.bridgeintelligent.tag.webserver.logs.entity.SearchLog;
import com.bridgeintelligent.tag.webserver.logs.mapper.SearchLogMapper;
import com.wayneleo.quickstart.framework.IDGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@Component
@AllArgsConstructor
@Slf4j
public class DimSearchLogsInterceptor implements HandlerInterceptor, WebMvcConfigurer {

    private SearchLogMapper searchLogMapper;
    @Override
    public void addInterceptors( InterceptorRegistry registry ) {
        registry.addInterceptor( this ).addPathPatterns( "/api/dimMgmt/dimList","/api/logs/dimSearch");
    }

    @Override
    public void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex ) throws Exception {
        Map<String, String[]> parameterMap = request.getParameterMap();
        String[] dimNames = parameterMap.get("dimName");
        String dimName=null;
        if(dimNames!=null&&dimNames.length>0){
            dimName = dimNames[0];
        }
        // 保存logs
        if(StringUtils.isNotBlank(dimName)){
            if(dimName.length()<=500){
                save(dimName);
            }else {
                log.info("标签搜索内容超长：{}",dimName);
            }
        }
    }

    private void save(String dimName){
        SearchLog searchLog = new SearchLog().setId(IDGenerator.gen()).setParam(dimName).setCreateTime(new Date());
        searchLogMapper.insert(searchLog);
    }
}
